package gin_frame

import (
	"encoding/json"
	"errors"
	"gitee.com/yijimu/gin-frame/core"
	"gitee.com/yijimu/gin-frame/utils"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"strings"
)

// IdReq 公用id请求参数,必填
type IdReq struct {
	Id uint32 `json:"id" form:"id"  example:"1" comment:"id" binding:"required"` //id
}

// IdNoRequiredReq 公用id请求参数,不必填
type IdNoRequiredReq struct {
	Id uint32 `json:"id" form:"id"  example:"1" comment:"id"` //id
}

// IdArrayReq 公用id数组列表请求参数,必填
type IdArrayReq struct {
	Id []uint32 `json:"id" form:"id"  example:"[1]" comment:"id" binding:"required"` //id
}

// BindValidParam  绑定and验证请求数据
//
//	type AdminLoginRequest struct {
//		UserName string `form:"username" json:"username" comment:"用户名" binding:"required"`
//		Password string `form:"password" json:"password" comment:"密码"  binding:"required"`
//	}
func BindValidParam(c *gin.Context, param interface{}) error {
	if err := c.ShouldBind(param); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok { // validator.ValidationErrors类型错误则进行翻译
			mapErrs := core.RemoveTopStruct(errs.Translate(core.Trans))
			sliceErrs := []string{}
			for _, e := range mapErrs {
				sliceErrs = append(sliceErrs, e)
			}
			return errors.New(strings.Join(sliceErrs, ";"))
		} else { // 非validator.ValidationErrors类型错误直接返回
			return errors.New("shouldBind err:" + err.Error())
		}
	}
	return nil
}

// BindBodyJson  绑定请求Body数据的json字符串
func BindBodyJson(c *gin.Context, param interface{}) error {
	body, err := utils.GinGetRequestBody(c)
	if err != nil {
		return err
	}

	if err = json.Unmarshal([]byte(body), &param); err != nil {
		return err
	}

	return nil
}
